import 'dart:convert';
import 'dart:io';
import 'dart:isolate';
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:open_file/open_file.dart';
import 'package:jyofservice/util/APPUpgrade.dart';
import 'package:jyofservice/util/SlideRoute.dart';
import 'package:jyofservice/util/webconfig.dart';
import 'package:jyofservice/yinsizhengce/AgreementPage.dart';
import 'package:package_info_plus/package_info_plus.dart';

import 'package:path_provider/path_provider.dart';
import 'package:progress_dialog_null_safe/progress_dialog_null_safe.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';

import 'UpdatePwdPage.dart';

class MinePage extends StatefulWidget {
  @override
  _MinePageState createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  late SharedPreferences sharedPreferences;
  String? phone;
  bool isloading = true;
  var _serviceVersionCode;
  String? downloadUrl;
  late ProgressDialog pr;
  String? _localPath;
  int _currProgress = 0;
  ReceivePort _port = ReceivePort();
  late String path;
  var currentVersion = "";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
      var currentVersionCode = packageInfo.version;
      if(mounted)

        setState(() {
          currentVersion = currentVersionCode.toString();
        });
    });
    _bindBackgroundIsolate();
    FlutterDownloader.registerCallback(downloadCallback);
    getInfo().then((onValue) {
      if (onValue != null) {
        if (mounted) {
          setState(() {});
        }
      }
    });
  }

  Future getInfo() async {
    sharedPreferences = await SharedPreferences.getInstance();
    phone = sharedPreferences.getString("username");
    return phone;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: const Color(0xFFF1F1F1),
        appBar: AppBar(
          title: Text(
            '个人中心',
            style: TextStyle(
                color: Colors.white, fontSize: ScreenUtil().setSp(40)),
          ),
          centerTitle: true,
        ),
        body: Stack(
          alignment: Alignment(0.5, 0.5),
          children: <Widget>[
            Column(
              children: <Widget>[
                SizedBox(
                  height: ScreenUtil().setHeight(30),
                ),
                Container(
                  color: Colors.white,
                  height: ScreenUtil().setHeight(110),
                  padding: const EdgeInsets.all(10),
                  child: GestureDetector(
                    onTap: () {},
                    child: Row(
                      children: <Widget>[
                        Icon(
                          Icons.person,
                          color: Colors.grey,
                        ),
                        Expanded(
                          flex: 1,
                          child: Text(
                            phone ?? "",
                            style: TextStyle(
                                fontSize: ScreenUtil().setSp(40),
                                color: Colors.black),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
                SizedBox(
                  height: ScreenUtil().setHeight(30),
                ),
                Container(
                  padding: const EdgeInsets.all(10),
                  width: ScreenUtil().screenWidth,
                  height: ScreenUtil().setHeight(110),
                  color: Colors.white,
                  child: GestureDetector(
                    onTap: () {
                      Navigator.of(context)
                          .push(SlideRoute().createRoute(UpdatePwdPage()));
                    },
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: Text(
                            '修改密码',
                            style: TextStyle(
                                fontSize: ScreenUtil().setSp(35),
                                color: Colors.black),
                          ),
                        ),
                        Icon(
                          Icons.keyboard_arrow_right,
                          color: Colors.grey,
                        ),
                      ],
                    ),
                  ),
                ),
                Container(
                  color: Colors.black12,
                  margin: const EdgeInsets.only(left: 10),
                  height: ScreenUtil().setHeight(2),
                ),
                Container(
                  padding: const EdgeInsets.all(10),
                  height: ScreenUtil().setHeight(110),
                  width: ScreenUtil().screenWidth,
                  color: Colors.white,
                  child: GestureDetector(
                    onTap: () {
                      Navigator.of(context)
                          .push(SlideRoute().createRoute(AgreementPage()));
                    },
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: Text(
                            '隐私协议',
                            style: TextStyle(
                                fontSize: ScreenUtil().setSp(35),
                                color: Colors.black),
                          ),
                        ),
                        Icon(
                          Icons.keyboard_arrow_right,
                          color: Colors.grey,
                        ),
                      ],
                    ),
                  ),
                ),
                Container(
                  color: Colors.black12,
                  margin: const EdgeInsets.only(left: 10),
                  height: ScreenUtil().setHeight(2),
                ),
                Container(
                  padding: const EdgeInsets.all(10),
                  height: ScreenUtil().setHeight(110),
                  width: ScreenUtil().screenWidth,
                  color: Colors.white,
                  child: GestureDetector(
                    onTap: () {
                      if (mounted) {
                        setState(() {
                          isloading = false;
                        });
                      }
                      AppUpgrade().getNewVersionApp(context).then((value) {
                        if(mounted) {
                          setState(() {
                            isloading = true;
                          });
                        }
                        if (value["upgrade"]) {
                          showDialog(
                              context: context,
                              barrierDismissible: false,
                              builder: (BuildContext context) {
                                return CupertinoAlertDialog(
                                  title: Text("是否更新"),
                                  content: Text(
                                    "检测到新版本",
                                    style: Theme.of(context)
                                        .textTheme
                                        .titleMedium!
                                        .copyWith(
                                        color: Theme.of(context)
                                            .textTheme
                                            .bodySmall!
                                            .color),
                                  ),
                                  actions: <Widget>[
                                    CupertinoDialogAction(
                                      child: const Text('下次再说'),
                                      onPressed: () {
                                        Navigator.pop(context, false);
                                      },
                                    ),
                                    CupertinoDialogAction(
                                      child: const Text('立即更新'),
                                      onPressed: () {
                                        Navigator.pop(context, false);
                                        if (Platform.isIOS) {
                                          _launchAppStore(
                                              WebConfig().ITUNSTORE);
                                        } else {
                                          downloadUrl = value["url"];
                                          _downloadApp(context);
                                        }
                                      },
                                    )
                                  ],
                                );
                              });
                        }else{
                          Fluttertoast.showToast(msg: "当前已是最新版本无需更新");
                          if(mounted) {
                            setState(() {
                              isloading = true;
                            });
                          }
                        }
                      });
                    },
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: Text(
                            '版本更新',
                            style: TextStyle(
                                fontSize: ScreenUtil().setSp(35),
                                color: Colors.black),
                          ),
                        ),
                        Icon(
                          Icons.keyboard_arrow_right,
                          color: Colors.grey,
                        ),
                      ],
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    alignment: Alignment.bottomCenter,
                    margin: EdgeInsets.only(bottom: 10),
                    child: Text('当前版本V$currentVersion',style: TextStyle(
                        color: Colors.black26,fontWeight: FontWeight.w600,
                        fontSize: ScreenUtil().setSp(28)),),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    AppUpgrade().logout(context);
                  },
                  child: Container(
                    alignment: Alignment.bottomCenter,
                    color: Colors.blue,
                    width: ScreenUtil().screenWidth,
                    child: Center(
                      child: Text(
                        '退出登录',
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: ScreenUtil().setSp(40)),
                      ),
                    ),
                    height: ScreenUtil().setHeight(100),
                  ),
                ),
              ],
            ),
            Offstage(
              offstage: isloading,
              child: SpinKitFadingCircle(
                color: Colors.blue,
                size: 50.0,
              ),
            )
          ],
        ));
  }

  void _unbindBackgroundIsolate() {
    IsolateNameServer.removePortNameMapping('downloader_send_port');
  }

  void _bindBackgroundIsolate() {
    bool isSuccess = IsolateNameServer.registerPortWithName(
        _port.sendPort, 'downloader_send_port');
    if (!isSuccess) {
      _unbindBackgroundIsolate();
      _bindBackgroundIsolate();
      return;
    }
    _port.listen((dynamic data) {

      final id = (data as List<dynamic>)[0] as String;
      final value = data[1];
      final progress = data[2] as int;

      final status;
      switch (value) {
        case 0:
          status = DownloadTaskStatus.undefined;
          break;
        case 1:
          status =  DownloadTaskStatus.enqueued;
          break;
        case 2:
          status =  DownloadTaskStatus.running;
          break;
        case 3:
          status =  DownloadTaskStatus.complete;
          break;
        case 4:
          status =  DownloadTaskStatus.failed;
          break;
        case 5:
          status =  DownloadTaskStatus.canceled;
          break;
        case 6:
          status = DownloadTaskStatus.paused;
          break;
        default:
          throw ArgumentError('Invalid value: $value');
      }

      if (status == DownloadTaskStatus.running) {
        pr.update(progress: progress.toDouble(), message: "正在更新版本，请等待…");
      }
      if (status == DownloadTaskStatus.failed) {
        if (pr.isShowing()) {
          pr.hide();
        }
      }
      if (status == DownloadTaskStatus.complete) {
        if (pr.isShowing()) {
          pr.hide();
        }
        OpenFile.open(path + "/" + WebConfig().APKNAME);

        FlutterDownloader.open(taskId: id);
      }
    });
  }

  _launchAppStore(url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }

// 获取安装地址
  Future<String?> _apkLocalPath() async {
    final directory = await getExternalStorageDirectory();
    _localPath = directory?.path.toString();
    return _localPath;
  }

  Future _downloadApp(BuildContext context) async {
    print("haha");
    pr = ProgressDialog(context, type: ProgressDialogType.download);
    pr.style(
      message: "下载中...",
      maxProgress: 100.0
    );
    if (!pr.isShowing()) {
      pr.show();
    }
    path = (await _apkLocalPath())! + '/Download';
    final saveDir = Directory(path);
    bool hasExisted = await saveDir.exists();
    if (!hasExisted) {
      saveDir.create();
    }
    FlutterDownloader.cancelAll();
    //下载
    final tastId = await FlutterDownloader.enqueue(
        url: downloadUrl!,
        fileName: WebConfig().APKNAME,
        savedDir: path,
        showNotification: true,
        openFileFromNotification: true);
  }

  @pragma('vm:entry-point')
  static void downloadCallback(id, status, progress) {
    print('Download task ($id) is in status ($status) and process ($progress)');

    final SendPort send =
    IsolateNameServer.lookupPortByName('downloader_send_port')!;
    send.send([id, status, progress]);
  }
}
